package com.bjpowernode.common.client;

import com.bjpowernode.mvc.model.dto.UploadFileDTO;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;

import java.io.IOException;

public class DfsClient {

    public static String HTTP_URL = "";


    //文件的初始化
    public void initDfs() throws MyException, IOException {
        //1、读取配置文件
        ClientGlobal.init("fdfs_client.conf");
    }


    //获取StorageClient
    public StorageClient getStorageClient() throws MyException, IOException {

        //1、创建TrackerServer跟踪器的服务器端,StorageServer存储器的服务器端
        TrackerServer trackerServer = null;
        StorageServer storageServer = null;

        //2、创建TrackerClient跟踪器的客户端,StorageClient存储器的客户端
        TrackerClient trackerClient = new TrackerClient();
        trackerServer = trackerClient.getTrackerServer();
        storageServer = trackerClient.getStoreStorage(trackerServer);
        return new StorageClient(trackerServer, storageServer);
    }


    //上传文件
    public void uploadFile(UploadFileDTO uploadFileDTO) {
        StorageClient storageClient = null;
        try {
            //获取storageClient
            storageClient = getStorageClient();

            //获取元数据
            NameValuePair[] meta = {
                    //扩展名
                    new NameValuePair("ext", uploadFileDTO.getExt()),
                    //宽
                    new NameValuePair("width", String.valueOf(uploadFileDTO.getWidth())),
                    //高
                    new NameValuePair("height", String.valueOf(uploadFileDTO.getHeight()))
            };

            String[] result = storageClient.upload_file(uploadFileDTO.getContent(), uploadFileDTO.getExt(), meta);
            if (result != null && result.length == 2) {
                //组
                uploadFileDTO.setGroup(result[0]);
                //文件ID
                uploadFileDTO.setFieldId(result[1]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭StorageClient
                storageClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //删除文件
    public int deleteFileDFS(String group, String fileId) {
        StorageClient storageClient = null;
        int result = -1;
        try {
            //获取storageClient
            storageClient = getStorageClient();
            result = storageClient.delete_file(group, fileId);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭StorageClient
                storageClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


}
